package com.example.javabasic.thread.suanfa;

import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntConsumer;

/**
 * @description 交替打印字符串
 * @Author Lin FuYuan
 * @date 2020/10/16
 */
public class FizzBuzz {
    private int n;
    private volatile int s = 1;

    public FizzBuzz(int n) {
        this.n = n;
    }

    // printFizz.run() outputs "fizz".
    public void fizz(Runnable printFizz) throws InterruptedException {

        while (s <= n) {
            synchronized (this) {
                if (s % 3 == 0 && s % 5 != 0) {
                    printFizz.run();
                    s++;
                    this.notifyAll();
                    continue;
                }
                this.wait();
            }
        }
    }

    // printBuzz.run() outputs "buzz".
    public void buzz(Runnable printBuzz) throws InterruptedException {

        while (s <= n) {
            synchronized (this) {
                if (s % 5 == 0 && s % 3 != 0) {
                    printBuzz.run();
                    s++;
                    this.notifyAll();
                    continue;
                }
                this.wait();
            }
        }
    }

    // printFizzBuzz.run() outputs "fizzbuzz".
    public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {

        while (s <= n) {
            synchronized (this) {
                if (s % 3 == 0 && s % 5 == 0) {
                    printFizzBuzz.run();
                    s++;
                    this.notifyAll();
                    continue;
                }
                this.wait();

            }
        }
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void number(IntConsumer printNumber) throws InterruptedException {

        while (s <= n) {
            synchronized (this) {
                if (s % 3 != 0 && s % 5 != 0) {
                    printNumber.accept(s);
                    s++;
                    this.notifyAll();
                    continue;
                }
                this.wait();
            }
        }

    }


}
